
# 创建一个ｊｗｔ返回值的函数　　，默认只有ｔｏｋｅｎ　
# 我们需要在把ｕｓｅｒｎａｍｅ和　ｕｓｅｒ＿ｉｄ加到返回值中
import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username': user.username,
        'user_id': user.id
    }


from django.contrib.auth.backends import ModelBackend

class UsernameMobileModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        # 1. 如果是 手机号 我们根据手机号进行查询
            # 如果是 用户名 我们根据用户名进行查询
        # 我们可以根据 username 输入的格式来判断, 如果满足 手机号的规则 我们就认为是手机号
        # 否则就是用户名
        try:
            if re.match('1[3-9]\d{9}',username):
                #手机号
                user = User.objects.get(mobile=username)

            else:
                #用户名
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None


        #2. 检测密码
        if user.check_password(password):
            return user

def get_user(username):
    try:
        if re.match('1[3-9]\d{9}', username):
            # 手机号
            user = User.objects.get(mobile=username)

        else:
            # 用户名
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    # 如果没有发生异常，则返回ｕｓｅｒ
    else:
        return user

class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):
        # try:
        #     if re.match('1[3-9]\d{9}',username):
        #         #手机号
        #         user = User.objects.get(mobile=username)
        #
        #     else:
        #         #用户名
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None


        user = get_user(username)

        #2. 检测密码
        if user is not None and user.check_password(password):
            return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None